package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.code.RedisCode;
import one.stand.config.CardPosterConfig;
import one.stand.entity.excel.BusinessExcelEntity;
import one.stand.enums.AuditStateEnums;
import one.stand.enums.LoginEnum;
import one.stand.model.*;
import one.stand.request.BusinessCardRequest;
import one.stand.response.BusinessCardResponse;
import one.stand.service.BusinessCardService;
import one.stand.service.CompanyAccontService;
import one.stand.service.WxMessageService;
import one.stand.service.WxSunCodeService;
import one.stand.util.ExportDataDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Administrator
 */
@Service
public class BusinessCardServiceImpl extends PublicBaseService implements BusinessCardService {



    @Autowired
    protected WxMessageService wxMessageService;

    @Autowired
    protected WxSunCodeService wxSunCodeService;

    @Autowired
    protected CompanyAccontService companyAccontService;

    /**
     * 审核名片
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> auditBusinessCard(BusinessCardRequest request) {
        log.info("审核名片参数：{}", JSON.toJSONString(request));
        if (request == null || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        // 查询公司购买服务数
        CompanyServiceModel companyServiceModel = companyServiceMapper.selectCompanyService(new CompanyServiceModel() {{
            setCompanyId(request.getCId().intValue());
            setType(1);
        }});
        if (companyServiceModel == null || companyServiceModel.getAvailableNum() <= 0) {
            return ResultModel.fail("可用名片数不足，请前去购买服务名片数~！");
        }
        // 修改名片状态
        BusinessCardModel model = new BusinessCardModel();
        model.setCardId(request.getCardId());
        model.setAuditState(request.getAuditState());
        model.setAuditRemark(request.getAuditRemark());
        r = businessCardMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            Integer serviceId = companyServiceModel.getServiceId();
            // 审核同意，更新公司购买名片服务记录
            if (request.getAuditState().equals(AuditStateEnums.APPLY_SUCCESS.getCode())) {
                companyServiceModel.setAvailableNum(companyServiceModel.getAvailableNum() - 1);
                companyServiceModel.setCreateTime(currentDate());
                companyServiceModel.setPurchaseType(1);
                companyServiceModel.setServiceId(null);
                r = companyServiceMapper.insertSelective(companyServiceModel);
                if (r > 0) {
                    // 修改之前的名片服务记录表为记录
                    companyServiceMapper.updateByPrimaryKeySelective(new CompanyServiceModel() {{
                        setType(0);
                        setServiceId(serviceId);
                    }});
                }
            }
            return ResultModel.success(true);
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<Map<String, Object>> selectCustomerList(BusinessCardRequest request) {
        log.info("查询用户列表参数：{}", JSON.toJSONString(request));
        BusinessCardModel model = new BusinessCardModel();
        model.setState(1);
        model.setIsDel(0);
        model.setUserType(request.getUserType());
        model.setName(request.getName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<BusinessCardModel> list = businessCardMapper.selectCustomerList(model);
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        PageInfo<CompanyModel> pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>(2);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<ExportDataDTO<BusinessExcelEntity>> selectCustomerListExport(BusinessCardRequest request) {
        log.info("导出用户列表参数：{}", JSON.toJSONString(request));
        List<BusinessCardModel> list = businessCardMapper.selectCustomerList(new BusinessCardModel(){{
            setState(1);
            setIsDel(0);
            setUserType(request.getUserType());
            setName(request.getName());
        }});
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<BusinessExcelEntity> excelEntities = new ArrayList<>();
        list.forEach(model -> {
            {
                BusinessExcelEntity excelEntity = new BusinessExcelEntity();
                BeanUtils.copyProperties(model, excelEntity);
                if(model.getCreateTime() != null) {
                    excelEntity.setCreateTime(formatter.format(model.getCreateTime()));
                }
                excelEntities.add(excelEntity);
            }
        });
        ExportDataDTO exportDataDTO = new ExportDataDTO();
        exportDataDTO.setSheetName("员工列表");
        exportDataDTO.setFileName("员工列表");
        exportDataDTO.setTitle("员工列表");
        exportDataDTO.setDataList(excelEntities);
        return ResultModel.success(exportDataDTO);
    }

    @Override
    public ResultModel<BusinessCardResponse> getCustomerInfo(BusinessCardRequest request) {
        log.info("查询用户信息信息参数：{}", JSON.toJSONString(request));
        if(request == null || request.getCardId() == null){
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model =  businessCardMapper.getCustomerInfo(new BusinessCardModel(){{
            setCardId(request.getCardId());
        }});
        BusinessCardResponse response = new BusinessCardResponse();
        if(model != null){
            BeanUtils.copyProperties(model,response);
        }
        return ResultModel.success(response);
    }

    @Override
    public ResultModel<Boolean> stopCustomer(BusinessCardRequest request) {
        if(request == null || request.getCardId() == null){
            return ResultModel.checkParamFail();
        }
        log.info("员工退出企业：{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if(request.getRoleId() > 0 && request.getCardId().equals(request.getMyCardId())){
            log.info("BOSS不能移除自己哦~！", request);
            return ResultModel.fail("BOSS不能移除自己哦~!");
        }
        if(request.getRoleId() <= 0 && !request.getCardId().equals(request.getMyCardId())){
            log.info("权限不足~！", request);
            return ResultModel.fail("权限不足~!");
        }
        // 查询公司购买服务数
        CompanyServiceModel companyServiceModel = companyServiceMapper.selectCompanyService(new CompanyServiceModel() {{
            setCompanyId(request.getCId().intValue());
            setType(1);
        }});
        if (companyServiceModel == null) {
            log.info("服务异常,未找到公司购买服务记录信息~！", request);
            return ResultModel.fail("操作失败，未找到公司购买服务记录信息~!");
        }
        CustomerModel model = new CustomerModel();
        model.setAscriptionId(request.getCardId().longValue());
        model.setIsDel(0);
        model.setCustomerState(1);
        List<CustomerModel> list = customerMapper.getCustomer(model);
        if (list != null && list.size() > 0) {
            log.info("该员工下有独立客户，无法移除", request);
            return ResultModel.fail("该员工下有独立客户，无法移除~!");
        }
        r = businessCardMapper.delBusinessCard(new BusinessCardModel() {{
            setIsDel(1);
            setCardId(request.getCardId());
        }});
        if (r > 0) {
            // 公司购买名片服务记录表
            Integer serviceId = companyServiceModel.getServiceId();
            companyServiceModel.setHistoryNum(companyServiceModel.getAvailableNum());
            companyServiceModel.setAvailableNum(companyServiceModel.getAvailableNum() + 1);
            companyServiceModel.setCreateTime(currentDate());
            companyServiceModel.setPurchaseType(3);
            companyServiceModel.setServiceId(null);
            r = companyServiceMapper.insertSelective(companyServiceModel);
            if (r > 0) {
                // 修改之前的名片服务记录表为记录
                companyServiceMapper.updateByPrimaryKeySelective(new CompanyServiceModel() {{
                    setType(0);
                    setServiceId(serviceId);
                }});
            }
            // 删除用户月目标数据
            userTaskMapper.delUserTask(new UserTaskModel() {{
                setCardId(request.getCardId());
            }});
            // 删除缓存
            batchDelToken(new ArrayList<BusinessCardModel>(){{
                add(new BusinessCardModel(){{
                    setUserId(request.getUserId().intValue());
                }});
            }});
            return ResultModel.success(true);
        }
        return ResultModel.fail();
    }

    @Async("asyncServiceExecutor")
    public ResultModel<Boolean> batchDelToken(List<BusinessCardModel> businessCardModelList) {
        Set<String> keyList=new HashSet<>();
        for (BusinessCardModel model : businessCardModelList) {
            if(model.getUserId() != null) {
                keyList.addAll(redisUtil.getKey(RedisCode.getImList(model.getUserId().longValue(), LoginEnum.CRM.getCode())));
                keyList.addAll(redisUtil.getKey(RedisCode.getUserWebSocketMessageRecord(model.getUserId()+"","*",LoginEnum.CRM.getCode())));
                keyList.addAll(redisUtil.getKey(RedisCode.getUnreadMessage(model.getUserId()+"","*",LoginEnum.CRM.getCode())));
                keyList.addAll(redisUtil.getKey(RedisCode.getUserLoginToken("*"+model.getUserId())));
            }
        }
        log.info("公司解散需要删除得key:{}", JSON.toJSONString(keyList));
        redisUtil.batchDel(keyList);
        return ResultModel.success(true);
    }

}
